# coding:utf-8
'''
Created on 2010-1-1

@author: Jason Green
@author-email: guileen@gmail.com
此包用于测试django应用的性能,为优化（Optimize）做准备
TODO: middleware benchmarks(provide as a interceptor )
TODO: view_method benchmarks(provide as an middle_ware)
TODO: http requests benchmarks
TODO: SEO, spider optimize

数据使用：RRDTOOLS, rrdcached (1.4 and newer only)
TODO: 学习 rrdtool create , rrdcached, rrdgrahp 等命令
TODO: 初始化 rrd文件的脚本
TODO: rrdcached client in python

'''


def intercept_middlewares(interceptors):
    from django.core.handlers.base import BaseHandler
    _orign_load_middleware=BaseHandler.load_middleware
    def _new_load_middleware(self):
        from djangosnippets.utils.interceptor import wrap_interceptors
        from django.core.urlresolvers import get_callable
        #load interceptors
        _interceptors = []
        for interceptor in interceptors:
            if(callable(interceptor)):
                _interceptors.append(interceptor)
            else:
                _interceptors.append(get_callable(interceptor))
            
            
        #use obj ,because of self._request_middleware is a flag,see below.
        obj = BaseHandler()
        _orign_load_middleware(obj)
        #
        request_middleware=[]
        self._view_middleware = []
        self._response_middleware = []
        self._exception_middleware = []
        
        for method in obj._request_middleware:
            request_middleware.append(wrap_interceptors(method, _interceptors))
        for method in obj._view_middleware:
            self._view_middleware.append(wrap_interceptors(method, _interceptors))
        for method in obj._response_middleware:
            self._response_middleware.append(wrap_interceptors(method, _interceptors))
        for method in obj._exception_middleware:
            self._exception_middleware.append(wrap_interceptors(method, _interceptors))

        # the comment from django source 
        # We only assign to this when initialization is complete as it is used
        # as a flag for initialization being complete.
        self._request_middleware = request_middleware
    #reset BaseHandler.load_middleware
    BaseHandler.load_middleware = _new_load_middleware

def initialize_middleware_bench():
    intercept_middlewares(['djangosnippets.contrib.bench.middleware.time_interceptor',])

